var http = require('http');
var fs = require('fs');
var url = require('url');
var siteName = "留言板";
var querystring = require('querystring');
var port = 80;
var ip = '127.0.0.1';
var mysql = require('mysql');
var client = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123',
    database:'messagebord',
    port: 3306
});
client.connect();
var server = http.createServer(function (request, response) {
	console.log(request.url)
	response.statusCode = 200;
	response.statusMessage = 'bu zhi dao';
	response.setHeader('Content-Type','text/html');
	var ext = request.url.substr(request.url.lastIndexOf('.')+1);
	var exts = {
		'html':'text/html',
		'css':'text/css',
		'jpg':'image/jpeg',
		'js':'text/javascript',
		'png':'image/png'
	}
	if (exts[ext]==null) {
		exts[ext] = 'text/plain'
	}
	response.setHeader('Content-Type',exts[ext]);
	var data = "404";
	var p = url.parse(request.url,true)
	if (p.pathname == '/index.html') {
		try{
			data = fs.readFileSync('.'+request.url,'utf-8')
			data = data.replace(/%title/g,siteName)
			/*item = fs.readFileSync('data.json','utf-8')
			item = JSON.parse(item)*/
			
			client.query('select * from messagebord', function(err, rows, fields) {
			    if (err) throw err;
			    item = rows;
			    var s = "";
				for (var i = 0; i <item.length; i++) {
				    s+='<div class="item">';
					s+='<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>';
					s+='<p>'+item[i].message+'<a href="/delmessage.html?id='+item[i].id+'"><form method="POST" action="/delmessage.html"><input id="del" type="button" value="删除"/>';
					s+='</form></a></p></div>'
				}
					data = data.replace(/%main/g,s)
					response.write(data);
					response.end();
			});	
		}catch(e){
			console.log(e)
		}	
	}else if (p.pathname == '/addmessage.html'){
		/*author = p.query.author
		message = p.query.message
		item = JSON.parse(fs.readFileSync('data.json','utf-8'))
		item.push({
			author:author,
			message:message,
			time:new Date()
		})
		item = JSON.stringify(item);
		fs.writeFileSync('data.json',item)
		response.writeHead(302,{
			'location':'/index.html'
		})*/
		var s = ''; 
	    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
	    request.on('data', function(chunk){    
	        s += chunk;
	    });
	    request.on('end', function(){    
	        s = querystring.parse(s);
			
			client.query('insert into messagebord values(null,"'+s.author+'","'+s.message+'","'+new Date()+'")', function(err, rows, fields){
			    if (err) throw err;
			    console.log(rows);
			});
			
	        /*item = JSON.parse(fs.readFileSync('data.json','utf-8'))
			item.push({
				author:s.author,
				message:s.message,
				time:new Date()
			})
			fs.writeFileSync('data.json',JSON.stringify(item))*/
			response.writeHead(302,{
				'location':'/index.html'
			})
			response.end();
		});	
	}else if (p.pathname == '/delmessage.html'){
		id = p.query.id
		/*item.splice(id,1)
		item = JSON.parse(fs.readFileSync('data.json','utf-8'))
		item = JSON.stringify(item)
		fs.writeFileSync('data.json',item)*/
	
		client.query('delete from messagebord where id='+id, function(err, rows, fields) {
		    if (err) throw err;
		    response.writeHead(302,{
			'location':'/index.html'
		});
		    response.end()
		});
		
	}
})
server.listen(port);
console.log('Server running at http://%s:%s/',ip,port);